<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class QyWechat{

	//微信参数
	private $appid = QYWX_APPID;
	private $appsecret = QYWX_SECRET;

    public function __construct(){
        $this->CI= &get_instance();
	}

    
	// 获取accessToken
	public function get_access_token(){
        $this->CI->load->model('configModel');
        $tokenName = "qy_access_token_". $this->appid;
        // 获取rmx_sys_config表的access_token
        $arr = $this->CI->configModel->get_config_info($tokenName, false);
        // 检查有效时间
        if(!empty($arr) && strtotime($arr['createtime']) + 6000 > time()) {
            // 有效就返回该token
            return $arr['config_value'];
        }
		//请求服务器
		$url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={$this->appid}&corpsecret={$this->appsecret}";
    	$result = json_decode(file_get_contents($url), true);
    	//抛错
    	if(isset($result['errcode']) && $result['errcode'] != 0) throw new Exception($result['errmsg']);
    	// 回写配置
        $this->CI->configModel->set_config_value($tokenName, $result['access_token']);
    	return $result['access_token'];
	}

	// 获取jsapi_ticket
    public function get_jsapi_ticket(){
    	$accessToken = $this->get_access_token($this->appid, $this->appsecret);
    	// 检查有效时间
        $ticketName = "qy_jsapi_ticket_". $this->appid;
        // 获取rmx_sys_config表的ticket
        $arr = $this->CI->configModel->get_config_info($ticketName, false);
        // 检查有效时间
        if(!empty($arr) && strtotime($arr['createtime']) + 6000 > time()) {
            // 有效就返回该token
            return $arr['config_value'];
        }
        // 请求服务器
    	$url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token={$accessToken}&type=jsapi";
        $result = json_decode(file_get_contents($url), true);

        if(ENV != 'local') {
            // 本地不校验
            //抛错
            if($result['errmsg'] != 'ok') throw new Exception($result['errmsg']);
        }

    	// 回写配置
        $this->CI->configModel->set_config_value($ticketName, $result['ticket']);
    	return $result['ticket'];
    }
    // 获取jssdk签名参数
    public function jssdk_data($url){
    	$data['noncestr'] = random_str(12);
    	$data['jsapi_ticket'] = $this->get_jsapi_ticket();
    	$data['timestamp'] = time();
    	$data['url'] = $url;
        $tdata = $data;
        foreach($tdata as $k => $v) {
            $tdata[$k] = $k. "=". $v;
        }
    	sort($tdata);
    	$data['signature'] = sha1(implode("&", $tdata));
        $data['appid'] = $this->appid;
    	return $data;
    }
  
    // post请求
    private function post_data($url, $data, $postJson = false){
        if($postJson) {
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        // curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 访问https，不验证证书下同
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        if($postJson) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data))
            );
        }

        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        return $data;
    }

	/**
	 * 输出xml字符
	 * @throws WxPayException
	**/
	private function to_xml($arr) {
		if(!is_array($arr) || count($arr) <= 0)
		{
    		throw new Exception("数组数据异常！");
    	}
    	
    	$xml = "<xml>";
    	foreach ($arr as $key=>$val)
    	{
    		if (is_numeric($val)){
    			$xml.="<".$key.">".$val."</".$key.">";
    		}else{
    			$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    		}
        }
        $xml.="</xml>";
        return $xml; 
	}

    /**
     * 将xml转为array
     * @param string $xml
     * @throws WxPayException
     */
	private function from_xml($xml) {	
		if(!$xml){
			throw new Exception("xml数据异常！");
		}
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		return $arr;
	}
}